'use strict';

/*
 *  教室管理
 */ 
const mongoose = require('mongoose');
const classroomModel = require('../models/classroom.model');
const ipcModel = require('../models/ipc.model');
const httpUtil = require('../utils/http');
const Code = require('../common/error_code');
const Util = require('../utils/hobot_util');

// 教室列表
async function classroom_list(ctx) {
    const params = ctx.request.body
    if(!params.page_size||!params.page_num){
        return ctx.error(Code.RET_USER_QUERY_ERR_PARAM);
    }
    let cdt = {
    };
    if (params.group_name) {
        cdt.group_name = { $regex: params.group_name };
    }
    if (params.campus_name) {
        cdt.campus_name = { $regex: params.campus_name };
    }
    if (params.name) {
        cdt.name = { $regex: params.name };
    }
    if (params.num) {
        cdt.num = { $regex: params.num };
    }
    if (params.address) {
        cdt.address = { $regex: params.address };
    }
    const classrooms = await Util.pageQuery(params.page_num, params.page_size, classroomModel,
        cdt, '', '', {_id: -1});
    ctx.success(Code.REQUEST_SUCCESS('查询成功'), {
        page_num: params.page_num,
        page_size: params.page_size,
        total: classrooms.total,
        result: classrooms.results
    });
}

// 新增教室
async function add_classroom(ctx){
    const params = ctx.request.body
    try{
        if(!params || typeof params !=='object') return ctx.error(Code.REQUEST_ERROR('请填写设备参数'))
        if(!params.name){
            return ctx.error(Code.REQUEST_ERROR('请填写教室名称'))
        }
        const checkData = await classroomModel.findOne({name:params.name})
        if(checkData){
            return ctx.error(Code.REQUEST_ERROR('教室名称已存在'))
        }
        const classroom_newId = new mongoose.Types.ObjectId();
        let deviceIds = params.device_ids||[]
        deviceIds = [...new Set(deviceIds)]
        const related_devices = []
        for(let id of deviceIds){
            const device = await ipcModel.findById(id)
            if(device.classroom_id) {
                return ctx.error(Code.REQUEST_ERROR_MODAL(`设备:${device.d_nm}(${device.device_num})已被教室:${device.classroom_name}(${device.classroom_num})绑定，如需使用请先和该教室解除绑定！`))
            }
            await ipcModel.findOneAndUpdate({_id:id},{
                group_id: params.group_id,
                group_name: (params.group_name||'').trim(),
                campus_id: params.campus_id,
                campus_name: (params.campus_name||'').trim(),
                classroom_id: classroom_newId,
                classroom_name: (params.name||'').trim(),
                classroom_num: (params.num||'').trim()
            })
            if(device&&device.device_status===0){
                related_devices.push({
                    device_id:id,
                    device_uuid:device.device_uuid,
                    device_name:device.d_nm,
                    device_type:device.d_tp
                })
            }
        }
        const roomParams = {
            _id: classroom_newId,
            group_id: params.group_id,
            group_name: (params.group_name||'').trim(),
            campus_id: params.campus_id,
            campus_name: (params.campus_name||'').trim(),
            name: (params.name||'').trim(),
            num: (params.num||'').trim(),
            address: params.address,
            related_devices
        }
        await classroomModel.create(roomParams)
        ctx.success(Code.REQUEST_SUCCESS('添加成功'))
    }catch(err){
        let message = err && err.message
        let msg, others = []
        if(message) {
           [ msg,...others ] = message.split(': ').reverse()
        }
        ctx.error(Code.REQUEST_ERROR(msg||'添加失败'))
    }
}

// 删除教室
async function delete_classroom(ctx){
    const params = ctx.request.body
    try{
        if(!params || typeof params !=='object' || !params._id) return ctx.error(Code.REQUEST_ERROR('请选择要删除的教室'))
        if(Array.isArray(params._id)){
            for(let id of params._id){
                const classroom = await classroomModel.findOneAndRemove({_id:id}) 
                const oldDeviceIds = (classroom.related_devices||[]).map(item=>item.device_id)
                // 移除绑定
                for(let old_id of oldDeviceIds){
                    await ipcModel.updateOne({_id:old_id},{
                        group_id: '',
                        campus_id: '',
                        group_name: '',
                        campus_name: '',
                        classroom_id: '',
                        classroom_name: '',
                        classroom_num: ''
                    })
                }
            }
        }else{
            const classroom = await classroomModel.findOneAndRemove({_id:params._id})
            const oldDeviceIds = (classroom.related_devices||[]).map(item=>item.device_id)
            // 移除绑定
            for(let old_id of oldDeviceIds){
                await ipcModel.updateOne({_id:old_id},{
                    group_id: '',
                    campus_id: '',    
                    group_name: '',
                    campus_name: '',
                    classroom_id: '',
                    classroom_name: '',
                    classroom_num: ''
                })
            }
        }
        return ctx.success(Code.REQUEST_SUCCESS('删除成功'))
    }catch(err){
        return ctx.error(Code.REQUEST_ERROR('删除失败'))
    }
}

// 更新设备
async function update_classroom(ctx){
    const params = ctx.request.body
    if(!params || typeof params !=='object') return ctx.error(Code.REQUEST_ERROR('请填写设备参数'))
        if(!params._id){
            return ctx.error(Code.REQUEST_ERROR('请选择要更新的教室'))
        }
        if(!params.name){
            return ctx.error(Code.REQUEST_ERROR('请填写教室名称'))
        }
        const classroom = await classroomModel.findById(params._id)
        if(!classroom){
            return ctx.error(Code.REQUEST_ERROR('该教室不存在'))
        }
        const checkData = await classroomModel.findOne({
            name:params.name,
            _id:{
                $ne: params._id
            }
        })
        if(checkData){
            return ctx.error(Code.REQUEST_ERROR('教室名称已存在'))
        }
        const oldDeviceIds = (classroom.related_devices||[]).map(item=>item.device_id)

        let deviceIds = params.device_ids||[]
        deviceIds = [...new Set(deviceIds)]
        const related_devices = []
        
        // 移除绑定
        for(let old_id of oldDeviceIds){
            if(!deviceIds.includes(old_id)){
                await ipcModel.updateOne({_id:old_id},{
                    group_id: '',
                    campus_id: '',
                    group_name: '',
                    campus_name: '',
                    classroom_id: '',
                    classroom_name: '',
                    classroom_num: ''
                })
            }
        }
        for(let id of deviceIds){
            const device = await ipcModel.findById(id)
            if(device.classroom_id&&device.classroom_id!==params._id) {
                return ctx.error(Code.REQUEST_ERROR_MODAL(`设备:${device.d_nm}(${device.device_num})已被教室:${device.classroom_name}(${device.classroom_num})绑定，如需使用请先和该教室解除绑定！`))
            }
            await ipcModel.findOneAndUpdate({_id:id},{
                group_id: classroom.group_id,
                campus_id: classroom.campus_id,
                group_name: classroom.group_name,//集团名称
                campus_name: classroom.campus_name,//校区名称
                classroom_id: classroom._id,
                classroom_name: classroom.name,
                classroom_num: classroom.num
            })
            if(device&&device.device_status===0){
                related_devices.push({
                    device_id:id,
                    device_uuid:device.device_uuid,
                    device_name:device.d_nm,
                    device_type:device.d_tp
                })
            }
        }
        const roomParams = {
            group_id: params.group_id,
            campus_id: params.campus_id,
            group_name: (params.group_name||'百家云集团').trim(),
            campus_name: (params.campus_name||'北京软件园校区').trim(),
            name: (params.name||'').trim(),
            num: (params.num||'').trim(),
            address: params.address,
            related_devices
        }
        
        await classroomModel.findByIdAndUpdate(params._id, roomParams)
        ctx.success(Code.REQUEST_SUCCESS('更新成功'))
}


exports.classroom_list = classroom_list
exports.add_classroom = add_classroom
exports.delete_classroom = delete_classroom
exports.update_classroom = update_classroom